﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ChaogePrinter
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private HttpListener _listener;

        public delegate void SendMessage(string msg);

        SendMessage send;

        public void SendMethod(string msg)
        {
            if (InvokeRequired)
            {
                Invoke(send, msg);
                return;
            }
            textBox1.Text += msg + "\r\n";

            //button1.PerformClick();
            TopMost = true;
            TopMost = false;
            new Printer().StartPrint();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            send = SendMethod;

            Start();
        }

        public void Start()
        {
            _listener = new HttpListener();
            var url = $@"http://localhost:9782/";
            _listener.Prefixes.Add(url);//结尾务必要有 /
            _listener.Start();


            Task.Run(Handled);
        }
        /// <summary>
        /// 响应处理
        /// </summary>
        private void Handled()
        {
            while (true)
            {
                try
                {
                    var context = _listener.GetContext();
                    send(1 + "");

                    context.Response.Close();
                }
                catch (Exception ex)
                {
                    //break;
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            TopMost = true;
            Debug.WriteLine("1");
            //MessageBox.Show(this, "1 Print");
            Debug.WriteLine("2");
            TopMost = false;
            new Printer().StartPrint();
            Debug.WriteLine("3");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            button1.PerformClick();
        }
    }
}
